//      PythonAddin.cpp
//      
//      Copyright 2011 Alexander Lebedinsky <pr0f.a7ex@gmail.com>
//      
//      Redistribution and use in source and binary forms, with or without
//      modification, are permitted provided that the following conditions are
//      met:
//      
//      * Redistributions of source code must retain the above copyright
//        notice, this list of conditions and the following disclaimer.
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following disclaimer
//        in the documentation and/or other materials provided with the
//        distribution.
//      * Neither the name of the  nor the names of its
//        contributors may be used to endorse or promote products derived from
//        this software without specific prior written permission.
//      
//      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//      "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//      LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
//      A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
//      OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//      SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//      LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//      DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
//      THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//      (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//      OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <Python.h>

#include <wchar.h>
#include <string>

#include "PythonAddin.h"
#include "config.c"
#include "dynload.h"

#include "ComponentBase.h"
#include "AddInDefBase.h"
#include "IMemoryManager.h"

#ifdef __cplusplus
extern "C" {
#endif

extern PyObject *
_PyImport_LoadDynamicModule(char *name, char *pathname, FILE *fp);

#ifdef __cplusplus
}
#endif

PyObject*
getPythonErrorDescr()
{
    PyObject *ptype, *pvalue, *ptraceback;
    PyObject *pRetStr = PyString_FromString("");
    PyObject *newPiece;
    
    PyErr_Fetch(&ptype, &pvalue, &ptraceback);
    /*
    Note: Retrieve the error indicator into three variables whose
          addresses are passed. If the error indicator is not set,
          set all three variables to NULL. If it is set, it will be
          cleared and you own a reference to each object retrieved.
          The value and traceback object may be NULL even when the
          type object is not.
    */
    if(ptype == NULL) /* No error occurred */
    {
        return 0;
    }
    else
    {
        newPiece = PyObject_Repr(ptype);
        if(newPiece)
            PyString_ConcatAndDel(&pRetStr, newPiece);
        if(pvalue)
        {
            newPiece = PyObject_Repr(pvalue);
            if(newPiece)
                PyString_ConcatAndDel(&pRetStr, newPiece);
        }
        if(ptraceback)
        {
            newPiece = PyObject_Repr(ptraceback);
            if(newPiece)
                PyString_ConcatAndDel(&pRetStr, newPiece);
        }
    }
    Py_XDECREF(ptype);
    Py_XDECREF(pvalue);
    Py_XDECREF(ptraceback);

    return pRetStr;
}
//---------------------------------------------------------------------------//
uint32_t
pyStrToWchar(wchar_t** Dest, PyObject* Source, uint32_t len)
{
    uint32_t res = 0;
    PyUnicodeObject *uni_source = (PyUnicodeObject*)PyUnicode_FromObject(Source);

    if(!len)
        len = PyUnicode_GetSize((PyObject*)uni_source) + 1;

    if(!*Dest)
        *Dest = new wchar_t[len];
    memset(*Dest, 0, len*sizeof(wchar_t));
    
    // wchar_t* source = new wchar_t[len];
    // memset(source, 0, len*sizeof(wchar_t));
    res = PyUnicode_AsWideChar(uni_source, *Dest, len*sizeof(wchar_t));
    if(res == -1)
    {
        delete[] *Dest;
        *Dest = NULL;
    }
    return res;
}
//---------------------------------------------------------------------------//
uint32_t
pyStrToShortWchar(WCHAR_T** Dest, PyObject* Source, uint32_t len)
{
    PyUnicodeObject *uni_source = (PyUnicodeObject*)PyUnicode_FromObject(Source);

    if(!len)
        len = PyUnicode_GetSize((PyObject*)uni_source) + 1;

    // uint32_t size = PyUnicode_GetSize(uni_source) + 1;
    uint32_t size = len;
    wchar_t* source = new wchar_t[size];
    memset(source, 0, size*sizeof(wchar_t));
    PyUnicode_AsWideChar(uni_source, source, size*sizeof(wchar_t));
    
    if(!*Dest)
        *Dest = new WCHAR_T[len];
    
    WCHAR_T* tmpShort = *Dest;
    uint32_t res = 0;
    
    memset(*Dest, 0, len*sizeof(WCHAR_T));
    do
    {
        *tmpShort++ = (WCHAR_T)*source++;
        ++res;
    }
    while (len-- && *source);

    return res;
}
//---------------------------------------------------------------------------//
uint32_t
pyUniToShortWchar(WCHAR_T** Dest, PyObject* Source, uint32_t len)
{
    PyUnicodeObject *uni_source = (PyUnicodeObject*)PyUnicode_FromObject(Source);
    
    if(!len)
        len = PyUnicode_GetSize(Source) + 1;

    wchar_t* source = new wchar_t[len];
    ::memset(source, 0, len*sizeof(wchar_t));
    PyUnicode_AsWideChar(uni_source, source, len*sizeof(wchar_t));
    
    if(!*Dest)
        *Dest = new WCHAR_T[len];
    
    WCHAR_T* tmpShort = *Dest;
    uint32_t res = 0;
    
    ::memset(*Dest, 0, len*sizeof(WCHAR_T));
    do
    {
        *tmpShort++ = (WCHAR_T)*source++;
        ++res;
    }
    while (len-- && *source);

    delete[] source;
    return res;
}
//---------------------------------------------------------------------------//
int
importDynamic(const char *modName, const char *fileName)
{
    static
    PyObject *pImp;
    PyObject *pModule;

    if(!pImp)
    {
        pImp = PyImport_ImportModule("imp");
        if(!pImp)
        {
            /* PyErr_Print();
            Py_FatalError("Can't import imp"); */
            return -1;
        }
    }

    pModule = PyObject_CallMethod(pImp, "load_dynamic", "(s, s)", modName, fileName);
    if(pModule == NULL)
    {
        /* PyErr_Print();
        Py_FatalError("Can't import module"); */
        return -1;
    }
    Py_DECREF(pModule);

    return 0;
}
//---------------------------------------------------------------------------//
wchar_t*
importDynModules(void)
{
    if(!PyImport_DynModules){
        return NULL;
    }
    
    struct _dyn_loadable *p;
    wchar_t *err = NULL;
    
    for (p = PyImport_DynModules; ; p++) {
        if (p->mod_name == NULL || p->mod_filename == NULL)
            break;
        if(!_PyImport_LoadDynamicModule(p->mod_name, p->mod_filename, NULL))
        {
            PyObject *pyErr = NULL;
            pyErr = getPythonErrorDescr();
            if(!pyErr) return NULL;

            pyStrToWchar(&err, pyErr);
            Py_DECREF(pyErr);
        }
    }
    return err;
}
//---------------------------------------------------------------------------//
uint32_t
convPyStrToTV_STR(tVariant* Dest, const PyObject* pyStrSource, IMemoryManager *m_iMemory)
{
    uint32_t iRes = 0;
    char *source = PyString_AsString((PyObject*)pyStrSource);
    uint32_t iStrLenWithZero = strlen(source) + 1;

    if(!m_iMemory)
    {
        return 0;
    }

    if(m_iMemory->AllocMemory((void**)&Dest->pwstrVal, iStrLenWithZero*sizeof(char)))
    {
        Dest->pstrVal   = strcpy(Dest->pstrVal, source);
        iRes            = strlen(Dest->pstrVal);
        Dest->strLen    = iRes;
    }
    return iRes;
}
//---------------------------------------------------------------------------//
uint32_t
convPyStrToTV_WSTR(tVariant* Dest, const PyObject* pyStrSource, IMemoryManager *m_iMemory)
{
    uint32_t iRes = 0;
    wchar_t *source;

    if(!m_iMemory)
    {
        return 0;
    }

    int isUnicode = PyUnicode_Check(pyStrSource);
    PyObject *pyUni = NULL;
    if(isUnicode)
    {
        pyUni = (PyObject*)pyStrSource;
    }
    else
    {
        pyUni = PyUnicode_FromEncodedObject((PyObject*)pyStrSource, NULL, "replace");
    }

    if(!pyUni)
        return 0;
    
    uint32_t iStrLenWithZero = PyUnicode_GetSize(pyUni) + 1;
    
    if(m_iMemory->AllocMemory((void**)&Dest->pwstrVal, iStrLenWithZero * sizeof(WCHAR_T)))
    {
        PyUnicode_AsWideChar((PyUnicodeObject*)pyUni, source, iStrLenWithZero*sizeof(wchar_t));
        memset(Dest->pwstrVal, 0, iStrLenWithZero*sizeof(WCHAR_T));

        WCHAR_T* tmpShort = Dest->pwstrVal;
        wchar_t* tmpSrc   = source; // source is readonly!
        do
        {
            *tmpShort++ = (WCHAR_T)*tmpSrc++;
            ++iRes;
        }
        while (iStrLenWithZero-- && *tmpSrc);
        Dest->wstrLen = iRes;
    }

    if(!isUnicode) /* pyUni not same object as pyStrSource */
        Py_DECREF(pyUni);
    
    return iRes;
}
//---------------------------------------------------------------------------//
void
convPyIntToTV_I4(tVariant* pDest, const PyObject* pySource)
{
    PyObject    *pyInt;
    int         isInt = PyInt_Check(pySource);

    if(PyLong_Check(pySource))
        pDest->lVal = PyLong_AsLong((PyObject*)pySource);
    else
    {
        if(PyInt_Check(pySource))
            pDest->lVal = PyInt_AS_LONG((PyObject*)pySource);
        else
            pDest->lVal = 0;
    }
    TV_VT(pDest) = VTYPE_I4;
}
